package uf.audit.util;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;

/**
 * 全局工具单元类
 * 
 * @author sunny
 *
 */
public class Utils {

	private static Map<String, Properties> propCachs = new HashMap<String, Properties>();

	private static Logger log;

	private static Logger getLogger() {
		if (log == null)
			log = Logger.getLogger(Utils.class);
		return log;
	}

	/**
	 * 采用cache，避免每次访问都要读取文件
	 * 
	 * @param cfgPath
	 * @return
	 * @throws Exception
	 */
	public static Properties getProperties(String cfgPath) throws Exception {
		Properties properties = propCachs.get(cfgPath);
		if (properties == null) {
			properties = new Properties();
			InputStream stream = Utils.class.getResourceAsStream(cfgPath);
			try {
				properties.load(stream);
				stream.close();
				propCachs.put(cfgPath, properties);
			} catch (Exception e) {
				getLogger().error(e.getMessage(), e);
				throw e;
			}
		}
		return properties;
	}

	public static boolean isLogin(Controller controller) {
		return controller.getSession(true).getAttribute(Consts.SESSION_USER_ID) != null;
	}

	public static void cleanLogin(Controller controller) {
		controller.getSession(true).removeAttribute(Consts.SESSION_USER_ID);
	}

	public static void setLogin(Controller controller, String userId) {
		controller.getSession(true)
				.setAttribute(Consts.SESSION_USER_ID, userId);
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> parseJson(String jsonText) {
		return (Map<String, Object>) JSON.parse(jsonText);
	}
}
